#include "STableSetDlg.h"
#include "STableColumnSet.h"
#include "../SCheckEx.h"
#include <QVBoxLayout>
#include <QGridLayout>
#include <QLabel>
#include <QFrame>
#include <QPushButton>

STableSetDlg::STableSetDlg(QWidget* parent, STableColumnSet* set)
	: SPopupWindow(parent), m_tableSet(set)
{
	setTitle(tr("表格设置"));
	QVBoxLayout* mainLayout = new QVBoxLayout();
	contentLayout()->addLayout(mainLayout);

	mainLayout->setContentsMargins(16, 0, 16, 8);
	mainLayout->setSpacing(8);

	QLabel* label = new QLabel(tr("设置需要显示的列："), this);
	mainLayout->addWidget(label);

	std::map<int, std::vector<ColumnInfo> > groups = set->groups();
	int groupIndex = 0;
	for (auto g : groups)
	{
		QGridLayout* grid = new QGridLayout();
		grid->setContentsMargins(0, 0, 0, 0);
		grid->setHorizontalSpacing(14);
		grid->setVerticalSpacing(4);
		mainLayout->addLayout(grid);

		int index = 0;
		int colIndex = 0;
		while (colIndex < g.second.size())
		{
			const ColumnInfo& ci = g.second[colIndex];
			if (ci.widthType == kFixed)
			{
				++colIndex;
				continue;
			}
			int row = index / 5;
			int col = index % 5;
			SCheckEx* check = new SCheckEx(ci.name, this);
			check->setFixedSize(130, 24);
			check->setSelectState(ci.hide ? Qt::Unchecked : Qt::Checked);
			check->setIndex(ci.curIndex);
			m_colShow[ci.curIndex] = !ci.hide;
			connect(check, &SCheckEx::stateChanged, this, &STableSetDlg::onCheckChanged);
			grid->addWidget(check, row, col);

			++index;
			++colIndex;
		}

		if (index > 0 && index % 5 != 0)//不满5列
			grid->addWidget(new QWidget(this), index / 5, index % 5);

		++groupIndex;
		if (groupIndex != groups.size())
		{
			QFrame* line = new QFrame(this);
			line->setFrameShadow(QFrame::Plain);
			line->setFixedHeight(1);
			line->setFrameShape(QFrame::HLine);
			line->setStyleSheet("background-color:#1A4444;border:none");
			mainLayout->addWidget(line);
		}
	}

	QPushButton* btn = addBtn(QMessageBox::Ok, tr("确定"));
	connect(btn, &QPushButton::pressed, this, &STableSetDlg::applyChange);

	btn = addBtn(QMessageBox::Cancel, tr("取消"));
	connect(btn, &QPushButton::pressed, this, QOverload<>::of(&QDialog::reject));

	btn = addBtn(QMessageBox::Apply, tr("恢复默认"));
	connect(btn, &QPushButton::pressed, this, &STableSetDlg::restoreDefault);

	resize(sizeHint());
}

void STableSetDlg::onCheckChanged(int index)
{
	m_colShow[index] = !m_colShow[index];
}

void STableSetDlg::applyChange()
{
	m_tableSet->applyChange(m_colShow);
	accept();
}

void STableSetDlg::restoreDefault()
{
	m_tableSet->restoreDft();
	accept();
}

